package com.butterfly.hotkey.dashboard.framework.netty;

import cn.hutool.core.util.StrUtil;
import com.butterfly.hotkey.common.factory.CommonFactory;
import com.butterfly.hotkey.common.netty.INettyMsgHandler;
import com.butterfly.hotkey.core.constant.Constants;
import com.butterfly.hotkey.core.model.msg.HotKeyMsg;
import com.butterfly.hotkey.core.util.FastJsonUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static com.butterfly.hotkey.dashboard.constant.FactoryConstant.HANDLER;

/**
 * 这里处理所有netty事件。
 *
 * @author wuweifeng wrote on 2019-11-05.
 */
public class DashboardServerHandler extends SimpleChannelInboundHandler<String> {

    private final static Logger log = LoggerFactory.getLogger(Constants.DASHBOARD);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String message) {
        if (StrUtil.isBlank(message)) {
            return;
        }
        // 处理各类消息
        HotKeyMsg hotKeyMsg = FastJsonUtil.parseObject(message, HotKeyMsg.class);
        byte msgType = hotKeyMsg.getMsgType();
        INettyMsgHandler handler = CommonFactory.getBean(HANDLER, msgType);
        if (handler == null) {
            return;
        }
        handler.handle(hotKeyMsg, ctx);

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("some thing is error , {}", cause.getMessage());
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        ctx.close();
        super.channelInactive(ctx);
    }

}
